package org.example.studyonline.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.studyonline.mapper.CourseMaterialMapper;
import org.example.studyonline.pojo.CourseMaterial;
import org.example.studyonline.service.CourseMaterialService;
import org.example.studyonline.utils.AliOssUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class CourseMaterialServiceImpl extends ServiceImpl<CourseMaterialMapper, CourseMaterial> implements CourseMaterialService {
    @Resource
    private CourseMaterialMapper courseMaterialMapper;
    @Override
    public void putMaterial(Integer chapterID, String type, MultipartFile filePath) throws Exception {
        CourseMaterial courseMaterial = new CourseMaterial();
        courseMaterial.setChapterID(chapterID);
        courseMaterial.setType(type);

        String OriginalFilename = filePath.getOriginalFilename();
        String filename = UUID.randomUUID().toString()+OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(filename, filePath.getInputStream());
        courseMaterial.setFilePath(url);
        courseMaterialMapper.insert(courseMaterial);
    }

    @Override
    public void updateMaterial(Integer materialID, Integer chapterID, String type, MultipartFile filePath) throws Exception {
        CourseMaterial courseMaterial = new CourseMaterial();
        courseMaterial.setMaterialID(materialID);
        courseMaterial.setChapterID(chapterID);
        courseMaterial.setType(type);

        String OriginalFilename = filePath.getOriginalFilename();
        String filename = UUID.randomUUID().toString()+OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(filename, filePath.getInputStream());

        courseMaterial.setFilePath(url);
        courseMaterialMapper.updateById(courseMaterial);
    }
}
